<template>
    <div class="content">
      <div class="content-head">
        <el-form :inline="true" :model="formInline" size="mini" class="head-form">
            <el-form-item label="车间">
                <el-select v-model="formInline.workshop" placeholder="请选择车间">
                    <el-option label="装配线" value="装配线"></el-option>
                    <el-option label="机加工" value="机加工"></el-option>
                    <el-option label="走心机" value="走心机"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="月份">
                <el-date-picker v-model="formInline.month" type="month" value-format="yyyy-MM" placeholder="选择月"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="default" @click="reset_btn">重置</el-button>
                <el-button type="primary" :loading="isSearchBtnLoading" @click="search_btn">查询</el-button>
                <el-button type="success" @click="export_btn" :loading="exportBtnLoading">导出</el-button>
            </el-form-item>
        </el-form>
      </div>
      <div class="content-main">
        <el-table :data="tableData" style="width: 100%" :max-height="tableMaxHeight" v-loading="isTableLoading">   
            <el-table-column prop="materialName" label="产品名称" width=""></el-table-column>   
            <el-table-column prop="materialCode" label="产品编码" width=""></el-table-column>   
            <el-table-column v-for="item,index in tableColumn" :prop="item.prop" :label="item.label" :key="index" width=""></el-table-column>    
        </el-table>
      </div>
      <div class="content-footer" v-if="false">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10,20,30,50,100]" :page-size="pageSize" background layout="prev,pager,next,total,sizes,jumper" :total="total"></el-pagination>
      </div>
    </div>
</template>

<script>
import { reqMachineOutputForMonth,reqMachineOutputForMonthExpot } from "@/api/workOrder.js";
export default {
    name:"MachineMonthReport",  //产品月输出报表
    data(){
        return {
            formInline:{
                workshop:"机加工",
                month:this.formatDate()
            },
            tableColumn:[],
            tableData:[],
            isTableLoading:false,
            isSearchBtnLoading:false,
            exportBtnLoading:false,
            currentPage:1,
            pageSize:10,
            total:0,
            tableMaxHeight:450
        }
    },
    computed:{
        tableColumnList(){
            let month = this.formInline.month;
            const date = new Date(month);
            const y = date.getFullYear();
            const m = date.getMonth() + 1;
            const days = new Date(y,m,0).getDate();
            const dayList = [];
            for(let i = 0; i < days; i ++){
                const tmp = { prop:y + '-' + this.addZero(m) + '-' + this.addZero(i+1),label:m + '月' + (i + 1) + '日'};
                dayList.push(tmp);
            }
            return dayList;
        }
    },
    mounted(){
        this.calculateTableColumn();
        this.getMachineOutputForMonth();
        window.addEventListener("resize",this.calculateTableMaxHeight);
        this.calculateTableMaxHeight();
        document.title = "产品月报表";
    },
    beforeDestroy(){
        window.removeEventListener("resize",this.calculateTableMaxHeight);
    },
    methods:{
        //获取设备产出/月
        async getMachineOutputForMonth(){
            const dayArr = this.getStartAndEndDateBySelectMonth();
            const paramters = {workshop:this.formInline.workshop,startDate:dayArr[0],endDate:dayArr[1]};
            if(paramters.workshop === "" || paramters.startDate === ""){
                return;
            }
            this.isTableLoading = true;
            reqMachineOutputForMonth(paramters).then(response => {
                if(response.data.code === 200){
                    const tmp = response.data.data;
                    const tmpList = new Array();
                    for(let key in tmp){
                        const obj = {machine:key,...tmp[key]};
                        tmpList.push(obj);
                    }
                    this.tableData = tmpList;
                    this.isTableLoading = false;
                }
                this.isTableLoading = false;
                console.log('获取设备产出(月)',response);
            }).catch(error => {
                this.$message({type:"error",message:"列表数据获取失败"});
                console.log('获取设备产出(月)',error);
                this.isTableLoading = false;
            })
        },
        reset_btn(){
            this.formInline.workshop = "装配线";
            this.formInline.month = this.formatDate();
            this.calculateTableColumn();
            this.getMachineOutputForMonth();
        },
        async search_btn(){
            const {workshop,month} = this.formInline;
            if(workshop === "" || (month === "" || month === null)){
                this.$message({type:"info",message:"请选择车间或月份"});
                return;
            }
            this.isSearchBtnLoading = true;
            this.tableData = [];
            await this.calculateTableColumn();
            await this.getMachineOutputForMonth();
            this.isSearchBtnLoading = false;
        },
        export_btn() {
            const { workshop, month } = this.formInline;
            if(workshop === "" || month === "" || month === null){
            this.$message({type:"warning",message:"请选择月份、车间后再进行下载报表数据"});
                return;
            }
            const date = new Date(month);
            const y = date.getFullYear();
            const m = date.getMonth() + 1;
            const days = new Date(y,m,0).getDate();
            const startDate = y + "-" + this.addZero(m) + "-01";
            const endDate = y + "-" + this.addZero(m) + "-" + days;
            this.$confirm('即将导出当前内容', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'})
                .then(async () => {
                    this.exportBtnLoading = true;
                    let res = await reqMachineOutputForMonthExpot(workshop,startDate,endDate);
                    if (res.status === 200) {
                        let blob = res.data;
                        let url = window.URL.createObjectURL(blob,{type: 'application/zip'});
                        const aLink = document.createElement('a');
                        aLink.href = url;
                        let timestamp = new Date().getTime();
                        aLink.setAttribute('download', '设备产出月报表_' + timestamp);
                        document.body.appendChild(aLink);
                        aLink.click();
                        document.body.removeChild(aLink);
                        this.$message.success('导出成功');
                        this.exportBtnLoading = false;
                    } else {
                        this.$message.error('导出失败,请重试');
                        this.exportBtnLoading = false;
                    }
                    console.log('设备产出报表导出api',res);
                }).catch((error) => {
                    console.log("oee报表导出error:",error);
                    this.$message({type: 'info', message: '已取消导出!'});
                    this.exportBtnLoading = false;          
                });
        },
        async calculateTableColumn(){
            let month = this.formInline.month;
            const date = new Date(month);
            const y = date.getFullYear();
            const m = date.getMonth() + 1;
            const days = new Date(y,m,0).getDate();
            const dayList = [];
            for(let i = 0; i < days; i ++){
                const tmp = { prop:y + '-' + this.addZero(m) + '-' + this.addZero(i+1),label:m + '月' + (i + 1) + '日'};
                dayList.push(tmp);
            }
            this.tableColumn = dayList;
        },
        //根据选择的月份获取开始和结束日期
        getStartAndEndDateBySelectMonth(){
            const month = this.formInline.month;
            const date = new Date(month);
            const y = date.getFullYear();
            const m = date.getMonth() + 1;
            const days = new Date(y,m,0).getDate();
            const startDate = y + "-" + this.addZero(m) + "-01";
            const endDate = y + "-" + this.addZero(m) + "-" + days;
            return [startDate,endDate];
        },
        handleCurrentChange(page){
            this.currentPage = page;
        },
        handleSizeChange(size){
            this.pageSize = size;
        },
        calculateTableMaxHeight(){
            const dom = document.querySelector(".content-main");
            let h = dom.offsetHeight;
            this.$nextTick(() => {
                this.tableMaxHeight = h - 10;
            })
        },
        //格式化时间
        formatDate(value = new Date()){
            let date = value;
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            let day = date.getDate();
            let h = date.getHours();
            let m = date.getMinutes();
            let s = date.getSeconds();
            return year + "-" + this.addZero(month);
        },
        //补零函数
        addZero(value){
            return value >= 10 ? value : '0' + value;
        }
    }
}
</script>

<style lang='scss' scoped>
.content{
    width: 100%;
    height: 100%;
    padding: 1% 2%;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    .content-head{
        flex:1;
    }
    .content-main{
        flex:8;
    }
    .content-footer{
        flex:1;
        display: flex;
        justify-content: flex-end;
    }
}
</style>